//
//  ViewController.m
//  CAReplicatorLayerSurround
//
//  Created by Xwoder on 17/1/30.
//  Copyright © 2017年 Xwoder. All rights reserved.
//

#import "ViewController.h"
#import "UIView+ALQuickFrame.h"

#define BlueViewSideLength 50
#define OrangeViewSideLength 30

#define Radius 150

@interface ViewController ()

@property (nonatomic, weak) UIView *blueView;
@property (nonatomic, weak) UIView *orangeView;

@property (nonatomic, strong) CAReplicatorLayer *replicatorLayer;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIView *blueView = [[UIView alloc] init];
    blueView.backgroundColor = [UIColor blueColor];
    blueView.size = CGSizeMake(BlueViewSideLength, BlueViewSideLength);
    blueView.center = self.view.center;
    blueView.layer.cornerRadius = BlueViewSideLength / 2;
    blueView.layer.masksToBounds = YES;
    [self.view addSubview:blueView];
    self.blueView = blueView;
    
    UIView *orangeView = [[UIView alloc] init];
    orangeView.backgroundColor = [UIColor orangeColor];
    orangeView.size = CGSizeMake(OrangeViewSideLength, OrangeViewSideLength);
    orangeView.center = CGPointMake(blueView.center.x + Radius, blueView.center.y);
    orangeView.layer.cornerRadius = OrangeViewSideLength / 2;
    orangeView.layer.masksToBounds = YES;
    [self.view addSubview:orangeView];
    self.orangeView = orangeView;
    
    CAReplicatorLayer *replicatorLayer = [CAReplicatorLayer layer];
    [replicatorLayer addSublayer:blueView.layer];
    [replicatorLayer addSublayer:orangeView.layer];
    self.replicatorLayer = replicatorLayer;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 贝塞尔路径
    UIBezierPath *bezierPath = [UIBezierPath bezierPath];
    [bezierPath addArcWithCenter:self.blueView.center radius:Radius startAngle:0 endAngle:M_PI * 2 clockwise:YES];
    [bezierPath closePath];
    
    // 关键帧动画
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
    animation.keyPath = @"position";
    animation.path = bezierPath.CGPath;
    animation.duration = 10;
    animation.repeatCount = MAXFLOAT;
    
    // The number of copies to create, including the source layers.
    self.replicatorLayer.instanceCount = 20;
    // Specifies the delay, in seconds, between replicated copies. Animatable.
    self.replicatorLayer.instanceDelay = 0.5;
    
    [self.view.layer addSublayer:self.replicatorLayer];
    
    [self.orangeView.layer addAnimation:animation forKey:nil];
}

@end
